import { computed, nextTick, ref } from "vue"
// @ts-ignore
import { AddChatEvent, GetRobotIdHistoryChatList } from "@/api/memory"
import debounce from "@/utils/debounce"
import { ElMessage } from "element-plus"

export interface PaginationProps {
  page: number
  pageSize: number
  count: number
}

export interface ChatListProps {
  chatType: "user" | "bot"
  message: string
}

const PAGE_SIZE = 20
export default function useLive() {
  const pagination = ref<PaginationProps>({
    page: 1,
    pageSize: 0,
    count: 0
  })
  const chatBoolTextEnd = ref<boolean>(false)
  const loading = ref<boolean>(false)
  const immediate = ref<boolean>(false)
  const chatMainMessagesRef = ref<any>(null)
  const robotId = ref<number>(120)
  const chatCurrentList = ref<Partial<ChatListProps>[]>([])
  const userMessage = ref<string>("")

  // 页数
  const pageCount = computed(() => {
    return Math.ceil(pagination.value.count / PAGE_SIZE)
  })

  const initChatList = async () => {
    loading.value = true
    try {
      const { data } = await GetRobotIdHistoryChatList({ page: pagination.value.page, robot_id: robotId.value })
      pagination.value.count = data.count // 总数
      const chatList = data.list?.length > 0 ? data.list : ([] as ChatListProps[])

      // @ts-ignore
      const list = chatList.reduce((pur, cur) => {
        pur.push({ chatType: "user", message: cur?.question })
        pur.push({ chatType: "bot", message: cur?.answer || "暂未接收到上述问题，请重新提问~" })
        return pur
      }, [])
      // console.log('list :>> ', list);

      chatCurrentList.value = chatCurrentList.value.concat(list)
      nextTick(handleScrollToBottom)
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  const handleMessageEnter = debounce(async () => {
    if (chatBoolTextEnd.value) return
    const message = userMessage.value
    if (userMessage.value.trim() === "") {
      ElMessage({
        message: "问题不能为空！",
        type: "warning"
      })
      return
    }

    try {
      const res = await AddChatEvent({ robot_id: robotId.value, question: message })
      if (res.code === 200) {
        chatBoolTextEnd.value = true
        chatCurrentList.value.push({
          chatType: "user",
          message: userMessage.value
        })
        chatCurrentList.value.push({
          chatType: "bot",
          message: ""
        })
        handleScrollToBottom()
        userMessage.value = "" // 清空输入框
      } else {
        ElMessage({
          message: res.error || "发送失败",
          type: "error"
        })
        return
      }
    } catch (error: any) {
      console.error(error.message, "error")
      ElMessage({
        message: error.message || "发送失败",
        type: "error"
      })
    }
  }, 300)

  const handleScrollToBottom = () => {
    const chatMessageDom = chatMainMessagesRef.value as HTMLDivElement
    if (chatMessageDom) {
      nextTick(() => {
        chatMessageDom.scrollTop = chatMessageDom.scrollHeight
      })
    }
  }

  // 下一页
  const nextPage = debounce(() => {
    if (pagination.value.page >= pageCount.value) return
    immediate.value = true
    pagination.value.page += 1
    initChatList()
  }, 200)

  return {
    immediate,
    loading,
    pageCount,
    pagination,
    chatCurrentList,
    chatMainMessagesRef,
    userMessage,
    robotId,
    chatBoolTextEnd,
    handleScrollToBottom,
    initChatList,
    handleMessageEnter,
    nextPage
  }
}
